﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCSService;
using System.Text;
using SCS.Core.Models;
using SCS.Core.ViewModels;

namespace SCS.Core.Controllers
{
    public class ArticleController:BaseFontendController
    {
        #region "ArticleCategory"

        public ActionResult CategoryDetail(int id)
        {
            var type = Models.ModelsFontend.ArticaleModel.GetArticleCategory(id);
            ViewData["CategoryID"] = id;
            return View(type);
        }

        public StringBuilder GetListArticleCategoryBuilder(int? id)
        {
            StringBuilder sb = new StringBuilder();
            return ListArticleCategoryBuilder(ref sb, id);
        }

        public StringBuilder ListArticleCategoryBuilder(ref StringBuilder sb, int? id)
        {
            int siteGuid = GetSiteGuid();
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            List<SCSService.Article_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleCategoryByParentId(id,LanguageID,GetSiteGuid(),true);
            sb.Append("<ul>");
            foreach (var item in listCate)
            {
                if (DefaultHostGetter().Contains("localhost"))
                {
                    sb.Append("<li><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Article/ListArticle/" + item.CategoriesID + "'>" + item.CategoriesName + "</a></li>");
                }
                else
                {
                    sb.Append("<li><a href='/" + DefaultLanguageGetter() + "/Article/ListArticle/" + item.CategoriesID + "'>" + item.CategoriesName + "</a></li>");
                }

                List<SCSService.Article_Category> listChild = Models.ModelsFontend.ArticaleModel.GetListArticleCategoryByParentId(item.CategoriesID,LanguageID,GetSiteGuid(),true);
                if (listChild.Count() > 0)
                {
                    ListArticleCategoryBuilder(ref sb, item.CategoriesID);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        [ChildActionOnly]
        public ActionResult MenuArticle()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["MenuArticle"] = GetListArticleCategoryBuilder(null);

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticle");

        }

        #endregion

        #region "Article"

        public ActionResult ArticleDetail(int id)
        {
            IntPage();
            return View();
        }
        
        public ActionResult ListArticles(int? id)
        {
            IntPage();
            return View();           
        }

        [ChildActionOnly]
        public ActionResult ArticleView(int id)
        {
            var art = Models.ModelsFontend.ArticaleModel.GetArticleByID(id);
            ViewData["ArticleID"] = id;

            //Tin liên quan
            List<Article> listArticle = new List<Article>();
            string pageName = DefaultPageName();
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string[] arr;
            int idParent = 0;
            string parentName="";
            if (pageName.ToLower() == "ArticleDetail".ToLower())
            {
                //page detail
                string urlOld = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "";
                if (urlOld != "" && urlOld.Contains("/ListArticles") && !urlOld.EndsWith("/ListArticles"))
                {
                    arr = urlOld.Split('/');
                    idParent = int.Parse(arr[arr.Length - 1]);
                }
                else
                {
                    var artFrontpage = Models.ModelsFontend.ArticaleModel.GetListArticleFrontpageByArticleID(id);
                    idParent = artFrontpage.FirstOrDefault().CategoriesID;
                }
            }


            if (idParent != 0)
            {
                parentName = Models.ModelsFontend.ArticaleModel.GetArticleCategory(idParent).CategoriesName??"";
                listArticle = Models.ModelsFontend.ArticaleModel.GetListArticleByCategory(idParent, LanguageID, siteGuid);
                int count = listArticle.Count(); 
                int index = new Random().Next(count);

                listArticle = listArticle.Skip(index).Take(6).ToList();
            }
            ViewData["ArticleAnother"] = listArticle;
            ViewData["idParent"] = idParent;
            ViewData["parentName"] = parentName;

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/ArticleView", art);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListArticle(int? id)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string paramNumberSliveArticle = LoadNodeConfigSite(siteGuid, "paramNumberSliveArticle");

            //Id đầu vào là cateId
            int currentPage = 1;
            int pageSize = 5;

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            if (paramNumberSliveArticle != string.Empty && currentPage==1)
            {
                pageSize =5+ int.Parse(paramNumberSliveArticle);
            }

            return ListArticle(currentPage, pageSize, null, id);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListArticle(int? currentPage, int? pageSize, string gridAction, int? id)
        {

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string paramNumberSliveArticle = LoadNodeConfigSite(siteGuid, "paramNumberSliveArticle");

            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                if (paramNumberSliveArticle != string.Empty)
                {
                    pageSize = 5 + int.Parse(paramNumberSliveArticle);
                }
                else
                    pageSize = 5;
            }

            ViewData["currentPage"] = currentPage;


            var query = Models.ModelsFontend.ArticaleModel.GetListArticleByCategory(id,LanguageID,GetSiteGuid()).AsQueryable();
            int totalRows = query.Count();
            int totalPages=0;
            if (paramNumberSliveArticle != string.Empty)
            {
                //totalPages = (int)Math.Ceiling(((double)totalRows) / (double)pageSize);
                if (currentPage == 1)
                {
                    totalPages = ((int)Math.Ceiling(((double)totalRows - ((double)pageSize)) / (double)pageSize)) + 1;
                }
                else
                {
                    totalPages = ((int)Math.Ceiling(((double)totalRows - ((double)pageSize + int.Parse(paramNumberSliveArticle))) / (double)pageSize)) + 1;
                }
                
            }
            else
            {
                totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            }
             
            if (totalPages != 1)
            {
                //paging

                if (paramNumberSliveArticle != string.Empty)
                {
                    //if (currentPage == 1)
                    //{
                    //    query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                    //            .Take(((int)pageSize));
                    //}
                    //else
                    //{
                    //    query = query.Skip((((int)currentPage - 1) * (int)pageSize) + int.Parse(paramNumberSliveArticle))
                    //            .Take(((int)pageSize));
                    //}
                    query = query.Skip((((int)currentPage - 1) * (int)pageSize) + int.Parse(paramNumberSliveArticle))
                                .Take(((int)pageSize));
                }
                else
                {
                    query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
                }               
                
            }

            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize,null);

            var result = query.ToList();

            if (query.Count() > 0)
            {

            }

            // Set up our ViewModel
            var viewModel = new ListArticleViewModels
            {
                ArticleItem = result,
                ArticleCategory = id != null ? Models.ArticaleMasterModel.GetArticleCategory((int)id) : null,
                currenPageValue = (int)currentPage
            };

            if (totalRows == 0)
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListArticle", new ListArticleViewModels()); 
            else
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListArticle", viewModel);
                
        }

        //[ChildActionOnly]
        //public ActionResult BannerListArticle( int? id)
        //{           
        //    int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
        //    string pageName = DefaultPageName();
        //    string[] arr;
        //    int idParent = 0;
        //    if (pageName.ToLower() != "ListArticles".ToLower())
        //    {
        //        //khong phai trang list article (trang detail)
        //        string urlOld = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "";
        //        if (urlOld != "" && urlOld.Contains("/ListArticles"))
        //        {
        //            arr = urlOld.Split('/');
        //            idParent = int.Parse(arr[arr.Length - 1]);
        //        }
        //    }
        //    else
        //    { 
        //        if(id!=null)
        //        {
        //            var list= Models.ModelsFontend.ArticaleModel.GetListArticleFrontpageByArticleID((int)id);
        //            if (list!=null && list.Count() > 0)
        //            {
        //                idParent = list.FirstOrDefault().CategoriesID;
        //            }
        //        }
                
        //    }

        //    if (idParent != 0)
        //    {
        //        id = idParent;
        //    }
        //    // Set up our ViewModel
        //    var viewModel = new ListArticleViewModels
        //    {
        //        //ArticleItem = result,
        //        ArticleCategory = id != null ? Models.ArticaleMasterModel.GetArticleCategory((int)id) : null
        //    };

        //        return PartialView("../BaseFontend/" + GetSiteGuid() + "/BannerListArticle", viewModel);

        //}
        #endregion

        #region "ArticleStaticCategory"

        public ActionResult StaticCategoryDetail(int id)
        {
            var type = Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(id);
            ViewData["CategoryID"] = id;
            return View(type);
        }

        public StringBuilder GetListArticleStaticCategoryBuilder(int? id)
        {
            StringBuilder sb = new StringBuilder();
            return ListArticleStaticCategoryBuilder(ref sb, id);
        }

        public StringBuilder ListArticleStaticCategoryBuilder(ref StringBuilder sb, int? id)
        {
            int siteGuid = GetSiteGuid();
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentId(id, LanguageID, GetSiteGuid(), true);
            sb.Append("<ul>");
            foreach (var item in listCate)
            {
                if (DefaultHostGetter().Contains("localhost"))
                {
                    sb.Append("<li><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Article/ListArticleStatic/" + item.StaticCategoryID + "'>" + item.StaticCategoryName + "</a></li>");
                }
                else
                {
                    sb.Append("<li><a href='/" + DefaultLanguageGetter() + "/Article/ListArticleStatic/" + item.StaticCategoryID + "'>" + item.StaticCategoryID + "</a></li>");
                }

                List<SCSService.Artilce_Static_Category> listChild = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentId(item.StaticCategoryID, LanguageID, GetSiteGuid(), true);
                if (listChild.Count() > 0)
                {
                    ListArticleStaticCategoryBuilder(ref sb, item.StaticCategoryID);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        [ChildActionOnly]
        public ActionResult MenuArticleStatic()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["MenuArticleStatic"] = GetListArticleStaticCategoryBuilder(null);

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleStatic");

        }

        //[ChildActionOnly]
        //public ActionResult MenuArticleStaticCategoryWithParam()
        //{
        //    int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
        //    int siteGuid = GetSiteGuid();
        //    string param = LoadNodeConfigSite(siteGuid, "paramMenuTabArticleStaticCategory");
        //    List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

        //    ViewData["MenuArticleStaticCategoryWithParam"] = listCate;

        //    ///return ket qua la 1 childAction tai 1 folder khac
        //    return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleStaticCategoryWithParam");

        //}

        #endregion

        #region "ArticleStatic"

        public ActionResult ArticleStaticDetail(int id)
        {
            IntPage();
            return View();
        }

        public ActionResult ListArticlesStatic(int? id,string param)
        {
            IntPage();
            return View();
        }

        [ChildActionOnly]
        public ActionResult ArticleStaticView(int? id)
        {
            SCSService.Article_Static art=new Article_Static();
            if (id != null)
            {
                art = Models.ModelsFontend.ArticaleModel.GetArticleStaticByID((int)id);
            }
            //Tin liên quan
            List<Article_Static> listArticleStatic = new List<Article_Static>();
            string pageName = DefaultPageName();
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string[] arr;
            int idParent = 0;
            string parentName = "";
            if (pageName.ToLower() == "ArticleStaticDetail".ToLower())
            {
                //page detail
                string urlOld = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "";
                if (urlOld != "" && urlOld.Contains("/ListArticlesStatic") && !urlOld.Contains("param"))
                {
                    arr = urlOld.Split('/');
                    idParent = int.Parse(arr[arr.Length - 1]);
                }
                else
                {
                    var artStaticFrontpage = Models.ModelsFontend.ArticaleModel.GetListArticleStaticFrontpageByArticleStaticID((int)id);
                    idParent = artStaticFrontpage.FirstOrDefault().StaticCategoryID;
                }
            }


            if (idParent != 0)
            {
                parentName = Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory(idParent).StaticCategoryName;
                listArticleStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(idParent, LanguageID, siteGuid, true);
                int count = listArticleStatic.Count();
                int index = new Random().Next(count);

                listArticleStatic = listArticleStatic.Skip(index).Take(6).ToList();
            }
            ViewData["ArticleAnother"] = listArticleStatic;
            ViewData["idParent"] = idParent;
            ViewData["parentName"] = parentName;

            ViewData["ArticleStaticID"] = id;

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/ArticleStaticView", art);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListArticleStatic(int? id,string param)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            //Id đầu vào là cateId
            int currentPage = 1;
            int pageSize = 5;

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;
            ViewData["param"] = param;

            return ListArticleStatic(currentPage, pageSize, null, id,param);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListArticleStatic(int? currentPage, int? pageSize, string gridAction, int? id, string param)
        {
            string url = Request.Url.ToString();
            if (param == null)
            {
                param = Request.QueryString["param"];
                
            }
            ViewData["param"] = param??"";
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 5;
            }

            ViewData["currentPage"] = currentPage;

            if (id == null && (param != null || param != string.Empty))
            { 
                //Lấy danh sách article theo cate với param là duy nhất
                var artCate = Models.ModelsFontend.ArticaleModel.GetListArticaleStaticCategoryBySiteGuidAndLanguageIDAndParam(LanguageID, GetSiteGuid(), param).FirstOrDefault();
                if (artCate != null)
                {
                    id = artCate.StaticCategoryID;
                }
            }
            IQueryable<Article_Static> query = null;

            if (param != null || param != string.Empty)
            {
                query = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategoryAndOnlyParam(id, LanguageID, GetSiteGuid(),param, true).AsQueryable();
                
            }
            else
            {
                query = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategoryNotParam(id, LanguageID, GetSiteGuid(), true).AsQueryable();
            }
             
            int totalRows = query.Count();

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }

            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize,param);

            var result = query.ToList();

            if (query.Count() > 0)
            {

            }

            // Set up our ViewModel
            var viewModel = new ListArticleStaticViewModels
            {
                ArticleStaticItem = result,
                ArticleStaticCategory = id != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory((int)id) : null
            };

            if (totalRows == 0)
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListArticleStatic", new ListArticleStaticViewModels());
            else
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListArticleStatic", viewModel);

        }

        //[ChildActionOnly]
        //public ActionResult BannerListArticleStatic(int? id)
        //{
        //    string pageName = DefaultPageName();
        //    string[] arr;
        //    int idParent = 0;
        //    if (pageName.ToLower() != "ListArticlesStatic".ToLower())
        //    {
        //        //khong phai trang list article (trang detail)
        //        string urlOld = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "";
        //        if (urlOld != "" && urlOld.Contains("/ListArticlesStatic"))
        //        {
        //            arr = urlOld.Split('/');
        //            idParent = int.Parse(arr[arr.Length - 1]);

        //        }
        //    }
        //    else
        //    {
        //        if (id != null)
        //        {
        //            var list = Models.ModelsFontend.ArticaleModel.GetListArticleStaticFrontpageByArticleStaticID((int)id);
        //            if (list != null && list.Count() > 0)
        //            {
        //                idParent = list.FirstOrDefault().StaticCategoryID;
        //            }
        //        }

        //    }

        //    if (idParent != 0)
        //    {
        //        id = idParent;
        //    }
        //    // Set up our ViewModel
        //    var viewModel = new ListArticleStaticViewModels
        //    {
        //        //ArticleStaticItem = result,
        //        ArticleStaticCategory = id != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory((int)id) : null
        //    };

            
        //        return PartialView("../BaseFontend/" + GetSiteGuid() + "/BannerListArticleStatic", viewModel);

        //}
        #endregion
    }
}
